package com.changlie.generator.index;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;

import com.changlie.generator.bean.ConfigInfo;

import freemarker.template.Template;

public class GenerateBean extends Generator {

	@Override
	protected void generate() {
		try {
			Template template = configuration.getTemplate(ConfigInfo.beanTemplate);
			
			String beanPath = System.getProperty("user.dir") + "/src/" + ConfigInfo.EntityPackage.replace(".", "/")
					+ "/";
			File filePath = new File(beanPath);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}

			String[] tableNames = ConfigInfo.tableNames.split(",");
			for (String names : tableNames) {
				String[] nameArr = names.split(":");
				String tableName = nameArr[0];
				String className = nameArr.length > 1 ? nameArr[1] : nameArr[0];
				/***  class name, the first letter is upper case. ***/
				className = className.substring(0, 1).toUpperCase() + className.substring(1);
				
				// 获取 bean Template 填充 数据
				Map<String, Object> beanTemplateData = getBeanTemplateData(tableName, className);
				beanTemplateData.put("tableName", tableName);
				
				String filePathOfBean = beanPath + "/" + className + ".java";
				File file = new File(filePathOfBean);
				if (!file.exists()) {
					file.createNewFile();
				}
				// show generated data
				Writer writer = new FileWriter(file);
				template.process(beanTemplateData, writer);
				writer.flush();
				writer.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
